﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using WssUtils;

//TODO 控制AudioSource 的控制器，由AudioManager 主控

/// <summary>
/// 音频控制器，控制单个音效，一般用于
/// 特效爆炸、武器发射 等固定点播放的音效。
/// UI界面音效和全局音效请使用AudioManager 播放
/// </summary>
[RequireComponent(typeof(AudioSource))]
[DisallowMultipleComponent]
public class AudioSourceCtrl : MonoBehaviour
{
    public static Action<bool> onSoundSettings = null;
    public static bool IsMuteAll = false;
    private AudioSource audioSource;

    [Tooltip("随机选取其中的音频播放")]
    public AudioClip[] clips;

    [Tooltip("连续播放音频,如果不勾选，那一个音频得播放完成才能再次播放")]
    public bool multiPlay = false;
    public bool autoPlay = true;

    [Range(0, 1)]
    public float randomPitch = 0;
    private float initalPitch = 0;

    private void Awake()
    {
        if (audioSource == null) audioSource = GetComponent<AudioSource>();
        audioSource.mute = IsMuteAll;
        initalPitch = audioSource.pitch;
        // audioSource.playOnAwake = autoPlay;
    }

#if UNITY_EDITOR
    [EditorButton]
    void TestPlay()
    {
        var audioSource = GetComponent<AudioSource>();
        audioSource.Play();

        onAudioSetting(AudioManager.Instance.canPlaySound);
    }

#endif

    private void OnEnable()
    {
        onSoundSettings += onAudioSetting;
        audioSource.clip = null;
    }

    private void OnDisable()
    {
        onSoundSettings -= onAudioSetting;
        audioSource.clip = null;
    }

    public void Play(string name)
    {
        for (int i = 0; i < clips.Length; i++)
        {
            if (clips[i].name == name)
            {
                this.audioSource.clip = clips[i];
                this.audioSource.Play();
                break;
            }
        }
    }
    

    public void Play(string name,float t)
    {
        for (int i = 0; i < clips.Length; i++)
        {
            if (clips[i].name == name)
            {
                this.audioSource.clip = clips[i];
                this.audioSource.Play();
                StartCoroutine(DelayHide(t));
                break;
            }
        }
    }
    
    private IEnumerator DelayHide(float time)
    {
        yield return new WaitForSeconds(time);
        this.audioSource.enabled = false;
        this.enabled = false;
    }
    
    public void onAudioSetting(bool mute)
    {
        if (audioSource)
        {
            audioSource.mute = mute;
        }
    }

}
